<?php

namespace App\Http\Controllers;

use App\Models\UserSetting;
use App\Models\SystemConfig;
use App\Models\Tenant;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class SettingController extends Controller
{
    protected $smsService;

    public function __construct(SmsService $smsService)
    {
        $this->smsService = $smsService;
    }

    /**
     * 获取用户设置
     */
    public function getUserSettings(Request $request)
    {
        try {
            $user = Auth::user();
            $userType = $this->getUserType($user);

            // 获取所有用户设置
            $settings = UserSetting::where('user_id', $user->id)
                ->where('user_type', $userType)
                ->get()
                ->groupBy('setting_type')
                ->map(function ($group) {
                    return $group->pluck('setting_value', 'setting_key');
                });

            return response()->json([
                'success' => true,
                'data' => [
                    'settings' => $settings,
                    'user_info' => [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'phone' => $user->phone ?? $user->mobile,
                        'avatar' => $user->avatar
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('获取用户设置失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '获取用户设置失败'
            ], 500);
        }
    }

    /**
     * 更新个人信息
     */
    public function updatePersonalInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'avatar' => 'nullable|string|max:500'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = Auth::user();
            $userType = $this->getUserType($user);

            // 更新用户基本信息
            $user->update([
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone ?? $user->phone,
                'mobile' => $request->phone ?? $user->mobile,
                'avatar' => $request->avatar
            ]);

            // 保存扩展信息到设置表
            if ($request->has('address')) {
                UserSetting::setUserSetting(
                    $user->id,
                    $userType,
                    'address',
                    $request->address,
                    UserSetting::TYPE_PERSONAL
                );
            }

            return response()->json([
                'success' => true,
                'message' => '个人信息更新成功',
                'data' => [
                    'user' => $user->fresh()
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('更新个人信息失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '更新个人信息失败'
            ], 500);
        }
    }

    /**
     * 更新安全设置
     */
    public function updateSecuritySettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'settlement_verification_method' => 'required|in:sms,password,ip_whitelist',
            'ip_whitelist' => 'nullable|array',
            'ip_whitelist.*' => 'ip',
            'enable_two_factor' => 'boolean',
            'login_notification' => 'boolean'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = Auth::user();
            $userType = $this->getUserType($user);

            // 保存安全设置
            UserSetting::setUserSetting(
                $user->id,
                $userType,
                'settlement_verification_method',
                $request->settlement_verification_method,
                UserSetting::TYPE_SECURITY
            );

            if ($request->has('ip_whitelist')) {
                UserSetting::setUserSetting(
                    $user->id,
                    $userType,
                    'ip_whitelist',
                    $request->ip_whitelist,
                    UserSetting::TYPE_SECURITY
                );
            }

            UserSetting::setUserSetting(
                $user->id,
                $userType,
                'enable_two_factor',
                $request->get('enable_two_factor', false),
                UserSetting::TYPE_SECURITY
            );

            UserSetting::setUserSetting(
                $user->id,
                $userType,
                'login_notification',
                $request->get('login_notification', true),
                UserSetting::TYPE_SECURITY
            );

            return response()->json([
                'success' => true,
                'message' => '安全设置更新成功'
            ]);
        } catch (\Exception $e) {
            Log::error('更新安全设置失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '更新安全设置失败'
            ], 500);
        }
    }

    /**
     * 更新通知设置
     */
    public function updateNotificationSettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'task_notifications' => 'array',
            'task_notifications.sms' => 'boolean',
            'task_notifications.email' => 'boolean',
            'task_notifications.wechat' => 'boolean',
            'evaluation_notifications' => 'array',
            'settlement_notifications' => 'array',
            'system_notifications' => 'array'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = Auth::user();
            $userType = $this->getUserType($user);

            // 保存通知设置
            $notificationTypes = ['task_notifications', 'evaluation_notifications', 'settlement_notifications', 'system_notifications'];
            
            foreach ($notificationTypes as $type) {
                if ($request->has($type)) {
                    UserSetting::setUserSetting(
                        $user->id,
                        $userType,
                        $type,
                        $request->get($type),
                        UserSetting::TYPE_NOTIFICATION
                    );
                }
            }

            return response()->json([
                'success' => true,
                'message' => '通知设置更新成功'
            ]);
        } catch (\Exception $e) {
            Log::error('更新通知设置失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '更新通知设置失败'
            ], 500);
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
            'verification_code' => 'nullable|string|size:6'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = Auth::user();

            // 验证当前密码
            if (!Hash::check($request->current_password, $user->password)) {
                return response()->json([
                    'success' => false,
                    'message' => '当前密码不正确'
                ], 422);
            }

            // 如果启用了双因子认证，验证验证码
            $userType = $this->getUserType($user);
            $enableTwoFactor = UserSetting::getUserSetting($user->id, $userType, 'enable_two_factor', false);
            
            if ($enableTwoFactor && $request->has('verification_code')) {
                // 这里应该验证短信验证码，简化处理
                if (strlen($request->verification_code) !== 6) {
                    return response()->json([
                        'success' => false,
                        'message' => '验证码格式不正确'
                    ], 422);
                }
            }

            // 更新密码
            $user->update([
                'password' => Hash::make($request->new_password)
            ]);

            // 发送密码修改通知
            $loginNotification = UserSetting::getUserSetting($user->id, $userType, 'login_notification', true);
            if ($loginNotification && $user->phone) {
                $this->smsService->sendPasswordChangeNotification($user->phone, $user->name);
            }

            return response()->json([
                'success' => true,
                'message' => '密码修改成功'
            ]);
        } catch (\Exception $e) {
            Log::error('修改密码失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '修改密码失败'
            ], 500);
        }
    }

    /**
     * 获取系统配置（公开配置）
     */
    public function getSystemConfig(Request $request)
    {
        try {
            $configs = SystemConfig::getPublicConfigs();
            
            return response()->json([
                'success' => true,
                'data' => [
                    'configs' => $configs
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('获取系统配置失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '获取系统配置失败'
            ], 500);
        }
    }

    /**
     * 发送验证码
     */
    public function sendVerificationCode(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string|max:20',
            'type' => 'required|in:password_change,security_setting'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $user = Auth::user();
            
            // 验证手机号是否属于当前用户
            if ($user->phone !== $request->phone && $user->mobile !== $request->phone) {
                return response()->json([
                    'success' => false,
                    'message' => '手机号不匹配'
                ], 422);
            }

            // 发送验证码
            $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            $result = $this->smsService->sendVerificationCode($request->phone, $code);

            if ($result) {
                // 这里应该将验证码存储到缓存中，设置过期时间
                // Cache::put('verification_code_' . $request->phone, $code, 300); // 5分钟过期
                
                return response()->json([
                    'success' => true,
                    'message' => '验证码发送成功'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => '验证码发送失败'
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('发送验证码失败: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => '发送验证码失败'
            ], 500);
        }
    }

    /**
     * 获取用户类型
     */
    private function getUserType($user)
    {
        if ($user instanceof \App\Models\Tenant) {
            return 'tenant';
        } elseif ($user instanceof \App\Models\AdminUser) {
            return 'admin';
        } elseif ($user instanceof \App\Models\Freelancer) {
            return 'freelancer';
        }
        
        return 'unknown';
    }
}